<template>
  <div class="health-container">
    <van-nav-bar title="生理期管理" left-arrow @click-left="goBack" />
    
    <div class="content">
      <!-- 周期状态卡片 -->
      <div class="cycle-card">
        <div class="cycle-header">
          <h3>当前周期状态</h3>
          <van-tag type="primary">第 {{ currentDay }} 天</van-tag>
        </div>
        <div class="cycle-info">
          <div class="cycle-item">
            <span class="label">预计下次经期</span>
            <span class="value">{{ nextPeriodDate }}</span>
          </div>
          <div class="cycle-item">
            <span class="label">周期长度</span>
            <span class="value">{{ cycleLength }} 天</span>
          </div>
        </div>
      </div>

      <!-- 日历组件 -->
      <div class="calendar-section">
        <van-calendar
          v-model:show="showCalendar"
          :default-date="currentDate"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="onDateConfirm"
        />
        <van-cell title="选择日期" :value="formatDate(currentDate)" @click="showCalendar = true" />
      </div>

      <!-- 症状记录 -->
      <div class="symptom-section">
        <van-cell-group title="今日症状记录">
          <van-cell title="经期状态" :value="periodStatus" @click="showPeriodPicker = true" />
          <van-cell title="症状" :value="symptomsText" @click="showSymptomPicker = true" />
          <van-cell title="情绪" :value="moodText" @click="showMoodPicker = true" />
          <van-cell title="备注" :value="note || '添加备注'" @click="showNoteDialog = true" />
        </van-cell-group>
      </div>

      <!-- 历史记录 -->
      <div class="history-section">
        <van-cell-group title="最近记录">
          <van-cell 
            v-for="record in recentRecords" 
            :key="record.date"
            :title="formatDate(record.date)"
            :label="getRecordLabel(record)"
            :value="record.periodStatus"
          />
        </van-cell-group>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div class="bottom-actions">
      <van-button type="primary" block @click="saveRecord">保存记录</van-button>
    </div>

    <!-- 选择器弹窗 -->
    <van-popup v-model:show="showPeriodPicker" position="bottom">
      <van-picker
        :columns="periodOptions"
        @confirm="onPeriodConfirm"
        @cancel="showPeriodPicker = false"
      />
    </van-popup>

    <van-popup v-model:show="showSymptomPicker" position="bottom">
      <van-picker
        :columns="symptomOptions"
        @confirm="onSymptomConfirm"
        @cancel="showSymptomPicker = false"
      />
    </van-popup>

    <van-popup v-model:show="showMoodPicker" position="bottom">
      <van-picker
        :columns="moodOptions"
        @confirm="onMoodConfirm"
        @cancel="showMoodPicker = false"
      />
    </van-popup>

    <!-- 备注输入弹窗 -->
    <van-dialog
      v-model:show="showNoteDialog"
      title="添加备注"
      show-cancel-button
      @confirm="onNoteConfirm"
    >
      <van-field
        v-model="tempNote"
        rows="3"
        autosize
        type="textarea"
        maxlength="200"
        placeholder="记录今天的特殊情况..."
      />
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { menstrualCycleApi } from '@/api/services'
import { initMqttClient, subscribeTopic, unsubscribeTopic, publishMessage } from '@/api/mqtt'

const router = useRouter()

// 基础数据
const currentDay = ref(12)
const cycleLength = ref(28)
const nextPeriodDate = ref('2024-01-15')
const currentDate = ref(new Date())
const minDate = ref(new Date(2023, 0, 1))
const maxDate = ref(new Date(2025, 11, 31))
const loading = ref(false)
const userId = ref(localStorage.getItem('userId') || '00000000-0000-0000-0000-000000000000')

// 状态管理
const showCalendar = ref(false)
const showPeriodPicker = ref(false)
const showSymptomPicker = ref(false)
const showMoodPicker = ref(false)
const showNoteDialog = ref(false)

// 用户输入数据
const periodStatus = ref('经期中')
const symptoms = ref(['腹痛', '情绪波动'])
const mood = ref('一般')
const note = ref('')
const tempNote = ref('')

// 选项数据
const periodOptions = [
  '经期前', '经期中', '经期后', '排卵期', '安全期'
]
const symptomOptions = [
  '腹痛', '头痛', '情绪波动', '乳房胀痛', '疲劳', '失眠', '食欲变化', '无特殊症状'
]
const moodOptions = [
  '很好', '好', '一般', '差', '很差'
]

// 最近记录
const recentRecords = ref([
  {
    date: new Date(2024, 0, 10),
    periodStatus: '经期中',
    symptoms: ['腹痛', '情绪波动'],
    mood: '一般'
  },
  {
    date: new Date(2024, 0, 9),
    periodStatus: '经期中',
    symptoms: ['腹痛'],
    mood: '差'
  }
])

// 计算属性
const symptomsText = computed(() => {
  return symptoms.value.length > 0 ? symptoms.value.join(', ') : '无症状'
})

const moodText = computed(() => {
  return mood.value
})

// 初始化数据
const initData = async () => {
  loading.value = true
  try {
    // 获取用户周期数据
    const cyclesResponse = await menstrualCycleApi.getCyclesByUserId(userId.value)
    if (cyclesResponse && cyclesResponse.length > 0) {
      const latestCycle = cyclesResponse[0]
      
      // 计算当前周期天数
      const startDate = new Date(latestCycle.startDate)
      const today = new Date()
      const diffTime = Math.abs(today - startDate)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      currentDay.value = diffDays
      
      // 更新周期长度
      if (latestCycle.cycleLength) {
        cycleLength.value = latestCycle.cycleLength
      }
      
      // 计算下次经期日期
      const nextDate = new Date(startDate)
      nextDate.setDate(nextDate.getDate() + cycleLength.value)
      nextPeriodDate.value = formatDate(nextDate)
      
      // 更新最近记录
      updateRecentRecords(cyclesResponse)
    }
  } catch (error) {
    console.error('获取周期数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 更新最近记录
const updateRecentRecords = (cycles) => {
  // 从API返回的数据中提取最近记录
  const records = []
  cycles.slice(0, 5).forEach(cycle => {
    if (cycle.symptoms && cycle.symptoms.length > 0) {
      cycle.symptoms.forEach(symptom => {
        records.push({
          date: new Date(cycle.startDate),
          periodStatus: cycle.flowIntensity || '经期中',
          symptoms: [symptom.symptomType],
          mood: '一般'
        })
      })
    }
  })
  
  if (records.length > 0) {
    recentRecords.value = records
  }
}

// MQTT消息处理
const handleMqttMessage = (message) => {
  console.log('收到MQTT消息:', message)
  if (message.type === 'cycle_update') {
    // 更新周期信息
    if (message.currentDay) currentDay.value = message.currentDay
    if (message.nextPeriodDate) nextPeriodDate.value = message.nextPeriodDate
    if (message.cycleLength) cycleLength.value = message.cycleLength
  }
}

// 初始化MQTT
const initMqtt = async () => {
  try {
    await initMqttClient()
    // 订阅用户专属主题
    subscribeTopic(`shelife/user/${userId.value}/cycle_update`, handleMqttMessage)
  } catch (error) {
    console.error('MQTT初始化失败:', error)
  }
}

// 方法
const goBack = () => {
  router.back()
}

const formatDate = (date) => {
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

const onDateConfirm = (date) => {
  currentDate.value = date
  showCalendar.value = false
}

const onPeriodConfirm = (value) => {
  periodStatus.value = value
  showPeriodPicker.value = false
}

const onSymptomConfirm = (values) => {
  symptoms.value = values
  showSymptomPicker.value = false
}

const onMoodConfirm = (value) => {
  mood.value = value
  showMoodPicker.value = false
}

const onNoteConfirm = () => {
  note.value = tempNote.value
  showNoteDialog.value = false
}

const getRecordLabel = (record) => {
  const symptoms = record.symptoms.join(', ')
  return `症状: ${symptoms} | 情绪: ${record.mood}`
}

const saveRecord = async () => {
  try {
    // 准备保存的数据
    const cycleData = {
      userId: userId.value,
      startDate: formatDate(currentDate.value),
      flowIntensity: periodStatus.value,
      cycleType: 'regular',
      cycleLength: cycleLength.value
    }
    
    // 保存周期记录
    const savedCycle = await menstrualCycleApi.createCycle(cycleData)
    
    // 如果有症状，保存症状记录
    if (symptoms.value.length > 0) {
      // 这里应该调用症状API，暂时在控制台打印
      console.log('保存症状:', symptoms.value)
    }
    
    // 发布MQTT消息
    publishMessage(`shelife/user/${userId.value}/cycle_update`, {
      type: 'cycle_update',
      currentDay: currentDay.value,
      nextPeriodDate: nextPeriodDate.value,
      cycleLength: cycleLength.value,
      timestamp: new Date().toISOString()
    })
    
    // 显示成功提示
    showToast('记录已保存')
    
    // 刷新数据
    initData()
  } catch (error) {
    console.error('保存记录失败:', error)
    showToast('保存失败，请重试')
  }
}

// 生命周期钩子
onMounted(() => {
  initData()
  initMqtt()
})

onUnmounted(() => {
  // 清理MQTT订阅
  unsubscribeTopic(`shelife/user/${userId.value}/cycle_update`, handleMqttMessage)
})
</script>

<style scoped lang="scss">
.health-container {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 70px;
}

.content {
  padding: 0 16px;
}

.cycle-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin: 16px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.cycle-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  
  h3 {
    margin: 0;
    font-size: 16px;
    color: #333;
  }
}

.cycle-info {
  display: flex;
  justify-content: space-between;
}

.cycle-item {
  display: flex;
  flex-direction: column;
  
  .label {
    font-size: 12px;
    color: #999;
    margin-bottom: 4px;
  }
  
  .value {
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }
}

.calendar-section,
.symptom-section,
.history-section {
  margin-bottom: 16px;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  background: white;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}
</style>